package adv42;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author oldliu
 * @since 1.0
 */
public class MapTest {

    public static void main(String[] args) {
        final Map<Integer, Integer> map = new HashMap<>();// 结果可能大于1000
        //final Map<Integer, Integer> map = new ConcurrentHashMap<>();// 结果可能大于1000
//        Map<Integer, Integer> map2 = Collections.synchronizedMap(map);
//        M m=new M(map2);
        M m = new M(map);
        Thread th[] = new Thread[4];
        for (int i = 0; i < th.length; i++) {
            th[i] = new Thread(m);
            th[i].start();
        }
        for (int i = 0; i < th.length; i++) {
            try {
                th[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(map.size() + ">>>>>>>>>>>>>>");
//        Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<Integer, Integer> kv = iterator.next();
//            System.out.println(kv.getKey()+","+kv.getValue());
//        }
    }
}

class M implements Runnable {
    private final Map<Integer, Integer> map;

    public M(Map<Integer, Integer> m) {
        this.map = m;
    }

    @Override
    public void run() {

        for (int i = 1; i <= 1000; i++) {
            synchronized (map) {
                map.put(i, i);
            }
            if (i % 100 == 0) {
                System.out.println(Thread.currentThread().getName() + " 存入了" + i);
            }

        }
    }
}
